#!/usr/bin/env python
#coding=utf-8

import cgi
import wsgiref.handlers
import logging
import sys

sys.path.append('modules')
from base import *
from models import *
from utils import *
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import urlfetch
from google.appengine.api import users
from google.appengine.api import memcache
from BeautifulSoup import BeautifulSoup
from google.appengine.ext.db import BadValueError

class UploadBuyer(BaseRequestHandler):

  def get(self):
    self.render('templates/admin/upload.html')

  def post(self):
    file = self.param('file')
    xmlSoup = BeautifulSoup(''.join(file))
    objs = xmlSoup('temp')
    
    buyers = []
    errors = []
    for obj in objs:
      if not obj.companynameen:
        continue
			
      try:
				companyName = formatString(obj.companynameen.string)
				if Buyer.isExistByCompanyName(companyName):
					continue
				
				buyer = Buyer()
				buyer.id = int(obj.id.string)
				
				if obj.kinden:
					buyer.category = formatString(obj.kinden.string)
				
				if obj.mainproducten:
					buyer.mainProduct = formatString(obj.mainproducten.string)
				
				if obj.regareaen2:
					buyer.country = formatString(obj.regareaen2.string)
				
				if obj.regareaen1:
					buyer.area = formatString(obj.regareaen1.string)
					
				if obj.companynameen:
					buyer.companyName = companyName
					
				if obj.adden:
					buyer.address = formatString(obj.adden.string)
					
				if obj.postcode:
					buyer.postCode = formatString(obj.postcode.string)
				
				if obj.tel:
					buyer.tel = formatString(obj.tel.string)
					
				if obj.fax:
					buyer.fax = formatString(obj.fax.string)
				
				if obj.mobile:
					buyer.mobile = formatString(obj.mobile.string)
					
				if obj.dszen:
					buyer.contactName = formatString(obj.dszen.string)
					
				if obj.email:
					buyer.email = formatString(obj.email.string)
				
				if obj.www:
					buyer.site = formatString(obj.www.string)
				
				buyer.put()
				buyers.append(buyer)
      except BadValueError, e:
				msg = '%s:error:%s' % (companyName, e)
				errors.append(msg)
				logging.error(msg)
				continue

    reloadMemCache()
    self.template_values.update({'buyers': buyers})
    if len(errors) > 0:
			self.template_values.update({'errors': errors})

    self.render('templates/admin/upload_ok.html')
  

class ReloadCache(BaseRequestHandler):

  def get(self):
		reloadMemCache()
		stats = memcache.get_stats()
		self.template_values.update({'stats': stats})
		self.render('templates/admin/reloadmemche.html')

class Index(BaseRequestHandler):

  def get(self):
    self.render('templates/admin/index.html')

  
def main():
  
  url_mapping = [
  		('/admin/', Index),
  		('/admin/uploadbuyer', UploadBuyer),
      ('/admin/reloadcache', ReloadCache),
  		]
  
  application = webapp.WSGIApplication(
  		url_mapping,
  		debug=True)
  wsgiref.handlers.CGIHandler().run(application)
  
if __name__ == "__main__":
  main()
